<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 熊义 <34512664@qq.com>
// +----------------------------------------------------------------------

/**
 * RestAdminBaseController控制器注意：
 * 请求接口，header必须带入字段：
 * Authorization 或 XX-Token，XX-Token=$token即可，Authorization要带“Bearer ”=Bearer $token
 * XX-Device-Type=web
 * 获得管理员id不能用cmf_get_current_admin_id()函数，要用类属性
 * $this->userId;
 * $this->user;
 * $this->userType;
 */

namespace app\xs\controller;

use think\facade\Db;
use app\xs\service\UserService;
use app\xs\service\XsgzService;
use app\xs\model\XmglZzjgUserModel;
use app\xs\model\XmglZzjgModel;
use app\xs\model\CmfRoleModel;
use app\xs\model\CmfRoleUserModel;
use app\xs\model\CmfUserModel;
use cmf\controller\RestAdminBaseController;

class ApiController extends RestAdminBaseController
{
    public function conf($name = '', $value = null){
        $d = [
            'presale'                   => 7,           //售前的角色id
            'presale_ks'                => 11,          //考试售前的角色id
            'presale_jx'                => 13,          //教学售前的角色id
            "executive"                 => 9,           //平台经理的角色id
            'salesman'                  => 8,           // 销售的角色Id
            'supervisor'                => 3,           // 主管的角色Id
            'majordomo'                 => 10,          // BU领导(总监)的角色ID
        ];
        return isset($d[$name]) ? $d[$name] : null;
    }

    /**
     * 获得当前已登录用户数据，包括组织机构 和 角色
     */
    public function getLoginUserInfo()
    {
        $user_id = $this->userId;

        $xzum = new XmglZzjgUserModel();
        $zzjgRes = $xzum->getZzjgArrByUserID($user_id);

        $crum = new CmfRoleUserModel();
        $roleRes = $crum->getRoleArrByUserID($user_id);

        $cum = new CmfUserModel();
        $userRes = $cum->find($user_id);

        $userRes['zzjg'] = $zzjgRes;
        $userRes['role'] = $roleRes;

        $this->success('当前登录用户信息', $userRes);
    }

    /**
     * 获取当前用户的所属组织机构
     */
    public function getUserZzjg()
    {
        $xzum = new XmglZzjgUserModel();
        $zzjg_list = $xzum->getZzjgArrByUserID($this->userId);
        if (empty($zzjg_list)) $this->error('');
        $this->success($zzjg_list);
    }

    /**
     * 取得组织机构列表
     */
    public function getZzjgList()
    {
        $param = $this->request->param();

        $pageNumber = $this->request->param('pageNumber', 1);
        $pageSize = $this->request->param('pageSize', 20);

        $xzm = new XmglZzjgModel();

        $res = $xzm->searchList($param, "*", $pageNumber, $pageSize);
        $this->success('ok', $res);
    }

    /**
     * 获得 当前用户所属机构的销售人员
     */
    public function getXsArr()
    {
        $user_id = $this->userId;

        $us = new UserService();
        $zzjgIdArr = $us->getUserZzjgIdArr($user_id);
        $list = $us->getZzjgRoleUserList($zzjgIdArr,$this->conf('salesman'));
        $this->success('200 ok', $list);
    }

    /**
     * 获得 当前用户所属机构的销售和售前人员
     */
    public function getXsAndShqArr()
    {
        $user_id = $this->userId;

        $us = new UserService();
        $zzjgIdArr = $us->getUserZzjgIdArr($user_id);

        $a[] = $this->conf('presale');
        $a[] = $this->conf('presale_ks');
        $a[] = $this->conf('presale_jx');
        $a[] = $this->conf('salesman');
        $list = $us->getZzjgRoleUserList($zzjgIdArr, $a);

        $this->success('200 ok', $list);
    }

    /**
     * 显示角色列表
     */
    public function getRoleList()
    {
        $param = $this->request->param();

        $pageNumber = $this->request->param('pageNumber', 1);
        $pageSize = $this->request->param('pageSize', 20);

        $crm = new CmfRoleModel();

        $res = $crm->getAll("", "*", $pageNumber, $pageSize);
        $this->success('ok', $res);
    }

    /**
     * 显示资源列表
     * 无参数，则取得当前用户当天的单据；
     * 输入参数：dj_date，用户角色为销售，则取得当前用户dj_date日期的单据
     * 输入参数：dj_date，用户角色包含平台经理，则取得当前平台的所有销售dj_date日期的单据
     * /api/xs/xsgz/index/id/1
     */
    public function index()
    {
        $xs = new XsgzService();
        $us = new UserService();

        $params = $this->request->param();

        $limit = [];        //分页数据
        $limit['pageNumber'] = isset($params['pageNumber']) ? $params['pageNumber'] : 1;
        $limit['pageSize'] = isset($params['pageSize']) ? $params['pageSize'] : 20;

        //参数为空，则取得当前用户当天的单据数据
        if (empty($params)) {
            $today = date('Y-m-d 00:00:00');
            $w = [
                ['dj_date', '=', $today],
                ['user_id', '=', $this->userId]
            ];
            $dj = $xs->getdj($w, $limit);
            if (empty($dj)) $this->error('没有数据');
            $this->success('200 ok', $dj);
        }

        //根据单据编码djbm取单据数据
        if (isset($params['djbm']) && count($params) == 1) {
            $w['djbm'] = $params['djbm'];
            $dj = $xs->getdj($w, $limit);
            if (empty($dj)) $this->error('没有数据');
            $this->success('200 ok', $dj);
        }

        //取得当前用户 某个日期的单据数据
        if (isset($params['djdate']) && count($params) == 1) {
            $w = [
                ['user_id', 'in', $this->userId],
                ['dj_date', '=', date('Y-m-d 00:00:00', $params['djdate'] / 1000)]
            ];
            $dj = $xs->getdj($w, $limit);
            if (empty($dj)) $this->error('没有数据');
            $this->success('200 ok', $dj);
        }

        $w = [];            //预定义条件

        $djbm = isset($params['djbm']) ?  $params['djbm'] : null;       //单据编码
        $djdate = isset($params['djdate']) ? date('Y-m-d 00:00:00', $params['djdate'] / 1000) : null;  //要求unixtime
        $zzjg_id = isset($params['zzjg_id']) ? $params['zzjg_id'] : null;   //要求数组
        $userid_arr = isset($params['userid']) ? $params['userid'] : null;   //要求数组

        //根据用户id号user_id 取此用户所有单据数据，并分页
        if (isset($params['userid'])) {
            $role_arr = $us->getUserRoleIdArr($this->userId);
            //dump($roles);
            //dump($this->userId);
            //dump($w['user_id']);
            if (in_array(9, $role_arr) || in_array(10, $role_arr)) {
                $w = [['user_id', 'in', $userid_arr]];
            } elseif (in_array($this->userId, $userid_arr)) {
                $w = [['user_id', 'in', $this->userId]];
            } else {
                $this->error('没有权限查看他人数据');
            }
        }

        //根据用户id号user_id 和 单据日期dj_date 取指定用户某个日期的单据数据
        if (isset($params['userid']) && isset($params['djdate'])) {
            $w['dj_date'] = date('Y-m-d 00:00:00', $params['djdate'] / 1000);
            $dj = $xs->getdj($w, $limit);
            if (empty($dj)) $this->error('没有数据');
            $this->success('200 ok', $dj);
        }

        //根据单据日期dj_date 和 平台zzjg_id 取指定平台某个日期的所有人员单据数据，并分页
        if (isset($params['djdate']) && isset($params['zzjg_id'])) {
            $limit['pageNumber'] = $params['pageNumber'];
            $limit['pageSize'] = $params['pageSize'];

            $w['dj_date'] = date('Y-m-d 00:00:00', $params['djdate'] / 1000);
            $w['zzjg_id'] = [$params['zzjg_id']];
        }

        $this->error('没有匹配的查询参数');
    }

    /**
     * 显示指定的 工作单据gzdj 资源
     *
     * @param  int $id
     */
    public function read($id) {}

    /**
     * 保存更新的 工作单据gzdj 资源
     *
     * @param  int $id
     */
    public function update($data) {}

    /**
     * 保存新建的 工作单据gzdj 资源
     */
    public function save()
    {
        $p = $this->request->param();

        $xs = new XsgzService();
        try {
            $res = $xs->save($p);
        } catch (\Exception $e) {
            $this->error($e->getMessage(), $e->getCode());
        }
        $this->success("save gzdj success", $res);
    }

    /**
     * 删除 工作单据gzdj 指定资源
     *
     * @param  int $id
     */
    public function delete($id)
    {
        $xs = new XsgzService();
        try {
            $xs->delete($id);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        $this->success("delete gzdj $id success");
    }

    /**
     * 保存更新 客户工作khgz 的资源
     *
     * @param  int $id
     */
    public function updateKhgz($data)
    {
        $xs = new XsgzService();
        try {
            $xs->updateKhgz($data);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        $this->success("update xs_khgz, {$data['id']} success");
    }

    /**
     * 删除 客户工作khgz 表指定资源
     *
     * @param  int $id
     */
    public function deleteKhgz($id)
    {
        $xs = new XsgzService();
        try {
            $xs->deleteKhgz($id);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        $this->success('delete khgz $id success');
    }

    /**
     * 保存更新 其它工作qtgz 的资源
     *
     * @param  int $id
     */
    public function updateQtgz($data)
    {
        $xs = new XsgzService();
        try {
            $xs->updateQtgz($data);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        $this->success("update xs_qtgz, {$data['id']} success");
    }

    /**
     * 删除 其它工作qtgz 表指定资源
     *
     * @param  int $id
     */
    public function deleteQtgz($id)
    {
        $xs = new XsgzService();
        try {
            $xs->deleteQtgz($id);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        $this->success('delete qtgz $id success');
    }

    /**
     * 保存更新 工作问题gzwt 的资源
     *
     * @param  int $id
     */
    public function updateGzwt($data)
    {
        $xs = new XsgzService();
        try {
            $xs->updateGzwt($data);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        $this->success("update xs_gzwt, {$data['id']} success");
    }

    /**
     * 删除 工作问题gzwt 表指定资源
     *
     * @param  int $id
     */
    public function deleteGzwt($id)
    {
        $xs = new XsgzService();
        try {
            $xs->deleteGzwt($id);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        $this->success('delete gzwt $id success');
    }
}
